import { Tooltip } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

import type { FC } from 'react';

import styles from './index.less';

interface Props extends React.Attributes {
  children: any;
}

const TextOverflow: FC<Props> = (props) => {
  const refEl = useRef<HTMLDivElement>(null);
  const [isShow, setIsShow] = useState(false);

  useEffect(() => {
    // 异步处理，判断是否需要展示气泡提示框
    (async () => {
      if (refEl.current) {
        const el = refEl.current;
        if (el.clientWidth < el.scrollWidth) {
          setIsShow(true);
        } else {
          setIsShow(false);
        }
      }
    })();
  }, [props.children]);

  return (
    <div className={styles.cTooltipOverflow} ref={refEl}>
      {isShow ? (
        <Tooltip placement="topLeft" title={props.children}>
          {props.children}
        </Tooltip>
      ) : (
        props.children
      )}
    </div>
  );
};

export default TextOverflow;
